package com.zut.demo1.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zut.demo1.model.Classinglog;
import com.zut.demo1.service.ClassinglogService;
import com.zut.demo1.utils.*;
import org.apache.poi.ss.usermodel.Workbook;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@RestController
public class ClassinglogController {

    @Autowired
    private ClassinglogService classinglogService;

    @RequestMapping("/getAllClassinglog")
    public Msg getAll(String page,String access_token,Classinglog classinglog) throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, BadPaddingException, InvalidKeyException, IllegalBlockSizeException {

        System.out.println(classinglog);
        PageHelper.startPage(Integer.parseInt(page),12);
        List<Classinglog> lists = classinglogService.getAll(classinglog);

        for (int i=0;i<lists.size();i++){
            System.out.println(lists.get(i).toString());
        }

        PageInfo<Classinglog> pageInfo = new PageInfo(lists);

        Access_Token teaData = new Access_Token();

        JsonUtil jsonUtil = new JsonUtil();
        //获取教师信息
        ArrayList teas = new ArrayList();
        for (int i=0;i<lists.size();i++){
            BufferedReader bufferedReader = new BufferedReader(teaData.getDatas(access_token,lists.get(i).getOptcode()));
            String output = "";
            String teacherData = "";
            while ((output = bufferedReader.readLine()) != null) {
                teacherData = teacherData + output;
            }
            teas.add(teacherData);
        }

        return Msg.success().add("pageinfo",pageInfo).add("teas",teas);
    }

    //获取access_token信息
    @RequestMapping("/get_access_token")
    public Msg getTeaData() throws IOException {

        //获取教师信息
        Access_Token access_token = new Access_Token();
        BufferedReader bufferedReader = new BufferedReader(access_token.PostMain());

        String output = "";
        String teacherData = "";
        while ((output = bufferedReader.readLine()) != null) {
            teacherData = teacherData + output + "\n";
        }
        return Msg.success().add("teacherData",teacherData);
    }

    @GetMapping("/countfangshi")
    public Msg count(String times){

        int count1 = classinglogService.countfangshi1(times);
        int count2 = classinglogService.countfangshi2(times);
        System.out.println("count2:"+count2);
        return Msg.success().add("count1",count1).add("count2",count2-count1);
    }


    @GetMapping("/getemNames")
    public Msg getrmname(String times){

        List<Classinglog> rmName = classinglogService.getrmName(times);
        return Msg.success().add("rmName",rmName);
    }

    //通过id删除上课日志
    @GetMapping("/deleteById")
    public Msg deleteById(String id){
        Classinglog classinglog = new Classinglog();
        classinglog.setId(id);

        int flag = classinglogService.deleteById(classinglog);

        return Msg.success().add("flag",flag);
    }

    /*
    *
    *  文件导出
     */
    @RequestMapping("/export")
    public void exportExcel(HttpServletResponse response,Classinglog classinglog) throws Exception{

       Workbook workbook = bigExcel(1,new ExportParams(null,"1"),null,classinglog);

       ExcelExportUtil.closeExportBigExcel();

       String filename = "上课日志信息"+new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date())+".xlsx";

        downLoadExcelController.downLoadExcel(filename,response,workbook);

    }
    private Workbook bigExcel(int pageNum, ExportParams params, Workbook workbook,Classinglog classinglog) {
        //分页查询数据
        PageHelper.startPage(pageNum,1000);

        List<Classinglog> classinglogList = classinglogService.findAllClassinglogByCondition(classinglog);

        PageInfo<Classinglog> pageInfo = new PageInfo<>();

        workbook = ExcelExportUtil.exportBigExcel(params,Classinglog.class, classinglogList);
        //如果不是最后一页，递归查询
        if (pageInfo.getPages() > pageNum) {
            bigExcel(pageNum + 1,params,workbook,classinglog);
        }
        return workbook;
    }

    /*
    * 文件下载
     */
    @RequestMapping("/downLoadFile")
    public String downLoadFile(HttpServletResponse response, @RequestParam("fileName") String filePathName){
        String path = "C:/file/"+filePathName;

        File file = new File(path);

        if (!file.exists()) return "error";
        try(
                InputStream inStream = new FileInputStream(path);
                OutputStream os = response.getOutputStream();
        ) {
            response.reset();
            response.setHeader("Content-Disposition", "attachment;fileName=" + URLEncoder.encode(path,"UTF-8"));
            byte[] buff = new byte[1024];
            int len = -1;
            while ((len = inStream.read(buff)) > 0) {
                os.write(buff, 0, len);
            }
            os.flush();
        } catch (Exception e) {
            e.printStackTrace();
            return "error";
        }
        return "more_jiaoshi";
    }

    /*
    *  文件导入到数据库
     */
    @RequestMapping("/importExcel")
    public Msg importExcel(HttpServletResponse response, @RequestParam("file") MultipartFile file) throws Exception{
        String name=file.getOriginalFilename();

        List<Classinglog> classinglogList = ExcelUtil.importExcel(file,0,1,Classinglog.class);

        int success_sum = 0;
        int error_sum = 0;
        for (int i=0;i<classinglogList.size();i++){
            if (isExitById(classinglogList.get(i))){
                success_sum += classinglogService.saveImportExcel(classinglogList.get(i));
            }else{
                error_sum++;
            }
        }
        return Msg.success().add("success_sum",success_sum).add("error_sum",error_sum);
    }

    //判断导入的数据是否存在于数据库中more_jiaoshi
    public boolean isExitById(Classinglog classinglog){
        return classinglogService.isExitById(classinglog);
    }



//    //条件查询上课日志
//    @RequestMapping("/getMsgBycondition")
//    public Msg getMsgBycondition(Classinglog classinglog,String page,String access_token) throws IOException {
//        System.out.println("classloging:"+classinglog);
//        PageHelper.startPage(Integer.parseInt(page),20);
//
//        List<Classinglog> lists = classinglogService.getMsgBycondition(classinglog);
//
//        PageInfo<Classinglog> pageInfo = new PageInfo(lists);
//
//        Access_Token teaData = new Access_Token();
//
//        JsonUtil jsonUtil = new JsonUtil();
//        //获取教师信息
//        List teas = new ArrayList();
//        for (int i=0;i<lists.size();i++){
//            BufferedReader bufferedReader = new BufferedReader(teaData.getDatas(access_token,lists.get(i).getOptcode()));
//            String output = "";
//            String teacherData = "";
//            while ((output = bufferedReader.readLine()) != null) {
//                teacherData = teacherData + output;
//            }
//            teas.add(teacherData);
//        }
//
//        return Msg.success().add("pageinfo",pageInfo).add("teas",teas);
//    }
}
